package com.zhehekeji.opsys.api.plugin.wechat.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhehekeji.opsys.api.plugin.wechat.enm.EventType;
import com.zhehekeji.opsys.api.plugin.wechat.enm.MsgType;
import com.zhehekeji.opsys.api.plugin.wechat.service.WechatManagerService;
import com.zhehekeji.opsys.api.plugin.wechat.util.XmlUtils;
import com.zhehekeji.opsys.api.service.manager.ActivityManagerService;

/**
 * @ClassName WechatListenCtrl
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2018-1-3   下午3:18:02
 */
@Controller
@RequestMapping("/wechatListen")
public class WechatListenCtrl {
	private static final Logger logger = LoggerFactory.getLogger(WechatListenCtrl.class);
	@Autowired
	private ActivityManagerService activityMangerService;
	@Autowired
	private WechatManagerService wechatManagerService;
	
	@RequestMapping(value="/receiveMsg",method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
	public void receiveMsg(HttpServletRequest request, HttpServletResponse response) throws IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		boolean isPost = request.getMethod().toLowerCase().equals("post");
		String rsp = "";
		PrintWriter out = null;
		try{
			if (isGet){
				rsp = checkSignature(request, response);
			}else{
				if (isPost){
					rsp = handlerMsg(request, response);
				}
			}
		}catch (Exception e){
			logger.error("处理消息失败", e);
		}finally{
			if (out != null){
				out.close();
				out = null;
			}
		}
		response.getWriter().write(rsp);
	}
	
	private String checkSignature(HttpServletRequest request, HttpServletResponse response){
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		String inMsg = "checkSignature [signature=" + signature + ", timestamp=" + timestamp + ", nonce=" + nonce + ", echostr=" + echostr + "]";
		logger.info(inMsg);
		
		String rspStr = "";
		if (!StringUtils.isBlank(echostr)){
			rspStr = echostr;
		}
		return rspStr;
	}
	
	private String handlerMsg(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String rspStr = StringUtils.EMPTY;
		Map<String, String> reqMap = XmlUtils.xmlToMap(request);
		String msgType = reqMap.get("MsgType");
		String event = reqMap.get("Event");
		String eventKey = reqMap.get("EventKey");
		String toUserName = reqMap.get("ToUserName");
		String fromUserName = reqMap.get("FromUserName");
		String inMsg = "handlerMsg [msgType=" + msgType + ", event=" + event + ", eventKey=" + eventKey + ", toUserName=" + toUserName + ", fromUserName=" + fromUserName + "]";
		logger.info(inMsg);
		if (StringUtils.isBlank(msgType)){
			return rspStr;
		}
		//场景值不加密：活动编码$用户账号$发送限制次数$中奖次数限制
		//场景值加密：加密密文
		if (StringUtils.isBlank(eventKey)){
			return rspStr;
		}
		if (!msgType.equals(MsgType.EVENT.getType())){
			return rspStr;
		}
		if (StringUtils.isBlank(event)){
			return rspStr;
		}
		if (!event.equals(EventType.SUBSCRIBE.getType()) && !event.contains(EventType.SCAN.getType())){
			return rspStr;
		}
		if (event.equals(EventType.SUBSCRIBE.getType())){
			eventKey = eventKey.replace("qrscene_", "");
		}
		synchronized (WechatListenCtrl.class) {
			rspStr = wechatManagerService.handler(msgType, event, eventKey, toUserName, fromUserName);
		}
		return rspStr;
	}
}

